<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use app\admin\library\Auth;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;

use fast\Tree;
/**
 * 广告报表数据
 *
 * @icon fa fa-circle-o
 */
class Advertisingreport extends Backend
{
    
    /**
     * Advertisingreport模型对象
     * @var \app\admin\model\Advertisingreport
     */
    protected $model = null;
    protected $rulelist = null;
    protected $dataLimit = 'auth';
    protected $dataLimitField = 'admin_id';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Advertisingreport;
        $this->view->assign("statusList", $this->model->getStatusList());

//         必须将结果集转换为数组
        $admin = Db::name('admin')->where('id', $this->auth->id)->find();
        if ($admin['launch'] == 1) {
            $ruleList = collection($this->model->where('admin_id',$this->auth->id)->order('createtime DESC')->select())->toArray();
        } else {
            $ruleList = collection($this->model->order('createtime DESC')->select())->toArray();
        }
        foreach ($ruleList as $k => &$v) {
            $v['name'] = __($v['name']);
        }
        Tree::instance()->init($ruleList);
        $this->rulelist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
        $ruledata = [0 => __('None')];
        foreach ($this->rulelist as $k => &$v) {
            $ruledata[$v['id']] = $v['name'];
            $v['name'] = str_replace(['&nbsp',';',' '],'',$v['name']);
        }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = count($this->rulelist);
            $lists =  $this->rulelist;
            if($lists){
                foreach ($lists as $k=>$v){
                    $admin = Db::name('admin')->where('id', '=', $v['admin_id'])->find();
                    if($admin){
                        $lists[$k]['admin_name'] = $admin['nickname'];
                    }else{
                        $lists[$k]['admin_name'] = '管理员已删除';
                    }
                }
            }
            $result = array("total" => $total, "rows" => $lists);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 导入
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        $fieldArr['Reporting starts'] = 'createtime';
        $fieldArr['Reporting ends'] = 'updatetime';
        $fieldArr['Account name'] = 'name';
        $fieldArr['Amount spent (USD)'] = 'amount';
        $fieldArr['Reach'] = 'reach';
        $fieldArr['Frequency'] = 'frequency';
        $fieldArr['Impressions'] = 'impressions';
        $fieldArr['Attribution setting'] = 'attribution';
        $fieldArr['Currency'] = 'currency';
        $fieldArr['CTR (link click-through rate)'] = 'click_rate';
        $fieldArr['Cost per purchase'] = 'shopping_costs';
        $fieldArr['CPM (cost per 1,000 impressions)'] = 'thousand_cost';
        
        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;
                    }
                }
                if ($row) {
                    if (!empty($row['createtime'])) {
                        $row['createtime'] = strtotime($row['createtime']);
                    }
                    if (!empty($row['updatetime'])) {
                        $row['updatetime'] = strtotime($row['updatetime']);
                    }
                    if (empty($row['name']) || $row['name'] == '-') {
                        $row['type'] = 1;
                        $row['name'] = '统计';
                        $inserts = $row;
                    }else{
                        $auth = Auth::instance();
                        $admin_ids = $auth->isLogin() ? $auth->id : 0;
                        $advertising_report = Db::name('advertising_report')
                            ->where('createtime', $row['createtime'])
                            ->where('name', $row['name'])
                            ->where('admin_id', $admin_ids)
                            ->find();
                        if (!empty($advertising_report)) {
//                            $msgs = '系统已有该条记录，本次导入无效';
                        }else{
                            $insert[] = $row;
                        }
                    }
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!empty($msgs)) {
            $this->error($msgs);
        }
        if (!$insert || !$inserts) {
            $this->error(__('No rows were updated'));
        }
        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                if (!isset($inserts['admin_id']) || empty($inserts['admin_id'])) {
                    $inserts['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                }
                //如果没有则添加 如果有则相加修改
                $wheres['type'] = '1';
                $wheres['createtime'] = $inserts['createtime'];
                $wheres['admin_id'] = $inserts['admin_id'];
                $reports = Db::name('advertising_report')->where($wheres)->find();
                if (!empty($reports)) {
                    $updates['reach'] = $reports['reach'] + $inserts['reach'];
                    $updates['impressions'] = $reports['impressions'] + $inserts['impressions'];
                    $updates['amount'] = $reports['amount'] + $inserts['amount'];
                    Db::name('advertising_report')->where('id',$reports['id'])->update($updates);
                    $report_id = $reports['id'];
                } else {
                    $report_id = Db::name('advertising_report')->insertGetId($inserts);
                }

                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                    $val['pid'] = $report_id;
                }
            }
            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }
}
